package com.inspinia.base.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 请求无证书 https 的链接工具类
 *
 * @author zhangy
 * @date 2018/6/28
 */
public class HttpsUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final class DefaultTrustManager implements X509TrustManager {

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }
    }

    /**
     * 获取https请求
     * @param requestUrl
     * @param params
     * @return
     */
    public static HttpsURLConnection doHttpsGet(String requestUrl,Map<String,String> params){
        HttpsURLConnection httpsConn = null;
        try {
            SSLContext ctx = null;
            try {
                ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            SSLSocketFactory ssf = ctx.getSocketFactory();
            String sendUrl = mapToUrl(requestUrl, params);
            URL url = new URL(sendUrl);
            httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
            httpsConn.setRequestMethod("GET");
            httpsConn.setRequestProperty("accept", "*/*");
            httpsConn.setRequestProperty("connection", "Keep-Alive");
            httpsConn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpsConn;
    }

    /**
     * 拼接map参数
     */
    public static String mapToUrl(String url, Map<String, String> params){
        int i = 0;
        StringBuilder builder = new StringBuilder();
        if (Objects.nonNull(params)){
            for (String key : params.keySet()){
               String val = params.get(key);
                if (i == 0){
                    url += "?" + key + "=" +val;
                }
               builder.append("&"+ key + "=" +val);
               i ++;
            }
            url += builder.toString();
        }
        return url;
    }

    /**
     * 读取 字节流
     * @param is
     * @return
     * @throws IOException
     */
    public static byte[] getBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] kb = new byte[1024];
        int len;
        while ((len = is.read(kb)) != -1) {
            baos.write(kb, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        is.close();
        return bytes;
    }

    /**
     * 解析响应流
     * @param is
     * @return
     */
    public static String resolveResponseEnity(InputStream is) throws IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder responseContent = new StringBuilder();
        String line = null;

        while((line=input.readLine()) != null) {
            responseContent.append(line);
        }
        return responseContent.toString();
    }

    public static void main(String[] args) throws IOException {
        Map<String,String> map = new HashMap<>();
        map.put("id","83bd2e7898222883e53e2f626b48cd45fa024b03");
        map.put("size",String.valueOf(10));
        map.put("page", String.valueOf(1));
        map.put("order","desc");
        map.put("orderKey","fupdate_time");
        map.put("appid","1");
        map.put("skey",DigestUtils.md5Hex(DigestUtils.md5Hex("1"+"4d2fc76211435f029271f1cf6d7eeae3")+System.currentTimeMillis()/1000));
        map.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        HttpsURLConnection httpCon = doHttpsGet("https://shenyang.qq.com//sha1/getIp", map);
        System.out.println(resolveResponseEnity(httpCon.getInputStream()));
    }
}
